package com.example.util;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.Socket;

/**
 * 基于apache commons pool实现的socket连接池使用
 * User: sunshow
 * Date: 13-4-27
 * Time: 上午11:25
 */
public class SocketConnectionFactory extends BasePoolableObjectFactory<Socket> {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String host;

    private int port;

    public SocketConnectionFactory(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public boolean validateObject(Socket socket) {
        if (socket.isClosed()) {
            return false;
        }
        if (!socket.isConnected()) {
            try {
                socket.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            return false;
        }
        /*
        try {
            socket.sendUrgentData(0xFF);
            return true;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);

            try {
                socket.close();
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }

            return false;
        }
        */
        return true;
    }

    @Override
    public void destroyObject(Socket socket) throws Exception {
        if (!socket.isClosed()) {
            socket.close();
        }
    }

    @Override
    public Socket makeObject() throws Exception {
        Socket socket = new Socket(this.getHost(), this.getPort());
        socket.setKeepAlive(true);
        return socket;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }
}
